const UserModel = require('../models/user')
const crypto = require('crypto')
const jwt = require('jsonwebtoken')

class UserController {
  /**
   * 
   * @param {*} ctx 
   * @returns {Promise<void>}
   */
  static async signup(ctx) {
    let req = ctx.request.body
    if (req.email && req.nickname && req.password && req.email) {
      try {
        let result = await UserModel.findUser(req.email)
        if (result) {
          ctx.response.status = 1001
          ctx.body = {
            code: 1001,
            msg: '邮箱已存在，请更换邮箱'
          }
        } else {
          let ret = await UserModel.createUser(req)
          ctx.response.status = 200
          ctx.body = {
            code: 200,
            msg: '注册成功，请登录',
            data: ret
          }
        }
      } catch (error) {
        ctx.response.status = 412
        ctx.body = {
          code: 412,
          msg: '创建失败',
          data: error
        }
      }
    } else {
      ctx.response.status = 416
      ctx.body = {
        code: 416,
        msg: '字段不全'
      }
    }
  }

  /**
   * 
   * @param {*} ctx 
   */
  static async signin(ctx) {
    let req = ctx.request.body
    if (req.email && req.password) {
      try {
        let result = await UserModel.findUser(req)
        if (result) {
          let pass = crypto.createHash('md5').update(req.password).digest('hex')
          let tokenInfo = {
            nickname: result.nickname,
            id: result.id,
            gender: result.gender
          }
          if (result.password === pass) {
            let secret = 'udxpe'
            let token = jwt.sign(tokenInfo, secret, {
              expiresIn: '1h'
            })
            ctx.response.status = 200
            ctx.body = {
              code: 200,
              msg: '登录成功',
              token: token
            }
          }
        }
      } catch (error) {
        ctx.response.status = 1003
        ctx.body = {
          code: 1003,
          msg: '登录失败',
          data: error
        }
      }
    } else {
      ctx.response.status = 412
      ctx.body = {
        code: 412,
        msg: '字段不全请勿提交'
      }
    }
  }
}

module.exports = UserController
